import React, { useCallback, useEffect, useState } from 'react'
import { Button, Checkbox, Form, Input, Space, Table, message, Popconfirm, Modal } from 'antd';
import type { TableProps } from 'antd';
import request from '../api/axios';
import { useNavigate } from 'react-router-dom';
import Com from '../hook/Hooks'
interface DataType {
  key: string;
  name: string;
  age: number;
  address: string;
  tags: string[];
}
type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};
function Index() {
  let nav = useNavigate()
  const [data, setData] = useState([])
  const [page, setPage] = useState(1)
  const [pageSize, setpageSize] = useState(10)
  const [total, setTotal] = useState(0)
  const [bjj, setBjj] = useState(false)
  const [title, setTitle] = useState('')
  const [form] = Form.useForm()
  const [forms] = Form.useForm()
  const getdata = async (title) => {
    let res = await request.get('/article/list', {
      params: {
        page,
        pageSize,
        keyword: title
      }
    })
    console.log(res)
    let { data } = res
    setData(data.rows)
    setTotal(data.count)
  }
  useEffect(() => {
    getdata()
  }, [page, pageSize])
  // 分页
  const change = (page: number, pageSize: number) => {
    setPage(page)
    setpageSize(pageSize)
  }
  // 删除
  const confirm: PopconfirmProps['onConfirm'] = useCallback((id) => {
    console.log(id);
    message.success('Click on Yes');
    const sc = data.filter(item => item.id !== id)
    setData(sc)
  }, [data])

  const cancel: PopconfirmProps['onCancel'] = (e) => {
    console.log(e);
    message.error('Click on No');
  };
  // 新增
  const [open, setOpen] = useState(false);
  const [confirmLoading, setConfirmLoading] = useState(false);
  const handleOk = async () => {
    let { id, title, content } = form.getFieldsValue()
    if (!bjj) {
      let res = await request.post('/article', {
        title,//文章标题
        content,//文章内容
        tagList: ["HTTP"],//标签  array[string]
        categoryList: ["HTTP"],//分类  array[string]
        "authorId": '47529555'//用户id 暂时写死47529555 登陆成功后返回的用户信息
      })
      console.log(res)
      setOpen(false)
      setConfirmLoading(false)
      getdata()
      form.resetFields()
    }
    else {
      let res = await request.put(`/article/${id}`, {
        title,//文章标题
        content,//文章内容
        tagList: ["HTTP"],//标签  array[string]
        categoryList: ["HTTP"],//分类  array[string]
        "authorId": '47529555'//用户id 暂时写死47529555 登陆成功后返回的用户信息
      })
      console.log(res)
      setOpen(false)
      setConfirmLoading(false)
      getdata()
      form.resetFields()
    }
  };

  const handleCancel = () => {
    console.log('Clicked cancel button');
    setOpen(false);
  };
  // 搜索
  const onFinish: FormProps<FieldType>['onFinish'] = (values) => {
    console.log('Success:', values);
    let { title } = values
    getdata(title)
  };

  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  // 编辑
  const bj = (row) => {
    setBjj(true)
    setOpen(true)
    form.setFieldsValue(row)
  }
  // 跳详情
  const handtz = (id) => {
    nav(`/detail/${id}`)
  }
  const columns: TableProps<DataType>['columns'] = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
      render: (text) => <a>{text}</a>,
    },
    {
      title: '内容',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '开始时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
    },
    {
      title: '内容',
      dataIndex: 'content',
      key: 'content',
    },
    {
      title: '结束时间',
      dataIndex: 'updatedAt',
      key: 'updatedAt',
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button onClick={() => handtz(record.id)}>查看</Button>
          <Button onClick={() => bj(record)}>编辑</Button>
          <Popconfirm
            title="Delete the task"
            description="Are you sure to delete this task?"
            onConfirm={() => confirm(record.id)}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <Button danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];
    return (
    <div>
      <Button onClick={() => setOpen(true)}>新增</Button>
      <Form
        name="basic"
        form={forms}
        layout='inline'
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 1200 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >

        <Form.Item
          label="详情"
          name="title"
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="内容"
          name="content"
        >
          <Input />
        </Form.Item>
        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            搜索
          </Button>
        </Form.Item>
      </Form>
      <Table<DataType> columns={columns} dataSource={data}
        pagination={{
          onChange: change,
          total: total,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `Total ${total} items`
        }}
      />
      <Modal
        title="Title"
        open={open}
        onOk={handleOk}
        confirmLoading={confirmLoading}
        onCancel={handleCancel}
      >
        <Form
          name="basic"
          form={form}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
          initialValues={{ remember: true }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item
            label="id"
            name="id"
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="详情"
            name="title"
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="内容"
            name="content"
          >
            <Input />
          </Form.Item>

        </Form>
      </Modal>
    </div>
  )
}

export default Com(Index)